package edu.zueb.sport.rest;

import edu.zueb.sport.dao.EquipmentMapper;
import edu.zueb.sport.entity.Equipment;
import edu.zueb.sport.exception.RestException;
import edu.zueb.sport.rest.api.Page;
import edu.zueb.sport.rest.api.RestResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@Tag(name = "器材类别管理", description = "器材类别管理")
@Slf4j
@RestController
@RequestMapping(EquipmentRestController.PATH_EQUIPMENT_TYPE)
public class EquipmentRestController {

    public static final String PATH_EQUIPMENT_TYPE = "/api/equipment";

    @Autowired
    EquipmentMapper equipmentMapper;

    @PostMapping(value = "/insert")
    public RestResponse<Equipment> insert(@RequestBody Equipment equipment) {
        try {
            equipmentMapper.insertEquipment(equipment);
        } catch (DuplicateKeyException e) {
            throw new RestException("器材已存在");
        }
        return RestResponse.success(equipment);
    }

    @PostMapping(value = "/list")
    public RestResponse<Page<Equipment>> listByPage(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "equipmentTypeId", required = false) Integer equipmentTypeId,
            @RequestParam(value = "brand", required = false) String brand,
            @RequestParam(value = "model", required = false) String model,
            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        int totalCount = equipmentMapper.countByPage(name, equipmentTypeId, brand, model);
        if (totalCount == 0) {
            return RestResponse.success(Page.empty());
        }
        List<Equipment> equipments = equipmentMapper.listByPage(name, equipmentTypeId, brand, model, pageNo, pageSize);
        return RestResponse.success(Page.asPage(totalCount, pageSize, equipments));
    }

    @PostMapping(value = "/update")
    public RestResponse<Equipment> update(@RequestBody Equipment equipment) {
        int rows = equipmentMapper.updateEquipment(equipment);
        if (rows != 1) {
            throw new RestException("更新失败");
        }
        return RestResponse.success(equipment);
    }

    @PostMapping(value = "/delete")
    public RestResponse<Boolean> delete(@RequestBody Equipment equipment) {
        int rows = equipmentMapper.deleteEquipment(equipment.getEquipmentId());
        if (rows != 1) {
            throw new RestException("删除失败");
        }
        return RestResponse.success(true);
    }
}
